package com.highspeed.bdk.gateway.netty.analyze.client;

import com.highspeed.bdk.gateway.entity.LuckHeader;
import com.highspeed.bdk.gateway.entity.LuckMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

@ChannelHandler.Sharable
public class LuckEncoder extends MessageToByteEncoder<LuckMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, LuckMessage message, ByteBuf out) throws Exception {

        // 将Message转换成二进制数据
        LuckHeader header = message.getLuckHeader();

        // 这里写入的顺序就是协议的顺序.

        // 写入Header信息

        out.writeChar(header.getStartTag());
        out.writeShort(header.getReqpacketId());

        out.writeBytes((TcpClientUtils.shortToByteArray(header.getOperType())));
        out.writeShort(header.getReserved());
        out.writeInt(header.getDataLen());
        message.setLuckHeader(header);
        // 写入消息主体信息
        out.writeBytes(message.getContent().toString().getBytes());
//        byte[] bytes = new byte[12];
//        out.writeBytes(,0,2)



        out.writeInt(message.getEnd());
    }

}
